package com.zhiwang.planet.ui.jsmodule

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Rect
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.webkit.JavascriptInterface
import androidx.core.content.FileProvider
import com.component.dly.xzzq_ywsdk.YwSDK
import com.component.dly.xzzq_ywsdk.YwSDK_WebActivity
import com.google.android.material.snackbar.Snackbar
import com.planet.processor.JsModule
import com.zhiwang.planet.App
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.di.ActivityScope
import com.zhiwang.planet.di.component.DaggerUtilComponent
import com.zhiwang.planet.event.PlayAdVideoEvent
import com.zhiwang.planet.event.TabChangeEvent
import com.zhiwang.planet.mvp.p.UtilPresenter
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.ui.BaseActivity
import com.zhiwang.planet.ui.entertain.MiniGameActivity
import com.zhiwang.planet.util.FormatUtil
import com.zhiwang.planet.util.Toaster
import com.zhiwang.planet.util.TokenManager
import com.zhiwang.planet.util.quickStartActivity
import kotlinx.android.synthetic.main.activity_photo_preview.*
import okio.*
import org.greenrobot.eventbus.EventBus
import java.io.BufferedOutputStream
import java.io.ByteArrayInputStream
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject

@JsModule
class SdkModule constructor(context: BaseActivity) : BaseJsModule(context) {


    @Inject
    lateinit var presenter: UtilPresenter

    init {

        DaggerUtilComponent.builder()
                .appComponent(context.getAppComponent())
                .build()
                .inject(this)

    }

    @JavascriptInterface
    fun navFishSdk() {

        Toaster.message("鱼玩盒子已下架")

//        YwSDK.init(
//                context.application,
//                "l1seq9x35hxol2qi644blibzh5qz4bng",
//                "1306",
//                TokenManager.webviewHeaderUserid(),
//                "1",
//                TokenManager.getDeviceId())
//        YwSDK_WebActivity.open(context)
    }


    /**
     * 播放短视频
     */
    @JavascriptInterface
    fun playVideoClips() {
        EventBus.getDefault().post(PlayAdVideoEvent)

    }


    @JavascriptInterface
    fun navMiniGame() {

//        EventBus.getDefault().post(TabChangeEvent(1))
        context.quickStartActivity(MiniGameActivity::class.java)
    }


    @JavascriptInterface
    fun saveImage2Album(imageData: String) {
        Toaster.message("sharing")

//        ShareModule(context).share("https://preview.qiantucdn.com/58pic/36/76/61/14r58PICG852b45JYUR6W_PIC2018.jpg!qt324new_nowater")

        var data: ByteArray = ByteArray(0)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            data = Base64.getMimeDecoder().decode(imageData.split(",")[1].toByteArray())
        }

        saveBase64Image2File(data)

    }

    fun saveBase64Image2File(byteArray: ByteArray): File {

        val fileHeader = byteArray.slice(0..8).toByteArray()
        val format = FormatUtil.getImageFormat(fileHeader)
        val fileName = SimpleDateFormat.getTimeInstance().format(Date()).plus(".$format")
        val filePath = File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "橡果赚钱" + File.separator + fileName)
        if (filePath.parentFile.exists().not()) filePath.parentFile.mkdirs()
        if (filePath.exists().not()) filePath.createNewFile()


        val bos = ByteArrayInputStream(byteArray)

        bos.source().buffer().readAll(filePath.sink(false))


        return filePath
    }


    fun broadcastAndShow(f: File) {
        MediaStore.Images.Media.insertImage(contentResolver,
                f.absolutePath, f.name, null)
        val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        val uri = Uri.fromFile(f)
        intent.data = uri
        sendBroadcast(intent)
        Snackbar.make(context.findViewById(android.R.id.content), "保存成功", Snackbar.LENGTH_LONG)
                .setAction("查看") {
                    val fileUri =
                            FileProvider.getUriForFile(context,
                                    BuildConfig.APPLICATION_ID,
                                    f)

                    //ACTION_VIEW 不支持微信;微信只支持ACTION_SEND，并且从EXTRA_STREAM读取文件
                    val starter = Intent(Intent.ACTION_VIEW)
                    starter.putExtra(Intent.EXTRA_STREAM, fileUri)
                    starter.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                            or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                            or Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    starter.setDataAndType(fileUri, "image/*")
                    startActivity(starter)
                }.show()
    }
}